import React ,{ useState } from 'react'
import { Field ,Button,Toast} from 'react-vant';
import {
    useSelector,
    useDispatch
} from "react-redux"
import * as api from "./api/index"
import "./index.scss"
import My_dialog from './components/My_dialog';

function Todulist() {
    const dispatch = useDispatch()
    const [visible, setVisible] = useState(false);
    const [value, setValue] = useState('');
    const [fromValue,setFromValue] = useState({})
    const data = useSelector((state) =>{
        return state.todulist_reducer.data
    })
    const add_data = () =>{
        let obj = {
            id:new Date().getTime(),
            value,
            date:new Date().toLocaleString()
        }
       dispatch(api.add_todulist(obj))
       setValue("")
    }

    const del_data = (id) =>{
        dispatch(api.del_todulist(id))
    }

    const edit_data = (obj) => {
        setFromValue(obj)
        setVisible(true)
    }

    const onCancel = () =>{
        setVisible(false)
    }
    const onConfirm = (values) =>{
        setVisible(false)
        console.log(values);
        dispatch(api.edit_todulist(values))
        Toast.info('点击确认按钮');
    }

    let my_dialog = {
        visible,
        onCancel,
        onConfirm,
        fromValue   
    }
    return (
        <div>
            <nav>
            <Field
                tooltip="提示tooltip"
                placeholder="请输入文本"
                value={value}
                onChange={setValue}
                />
             <Button type="primary" onClick={add_data}>添加</Button>
            </nav>
           <div>
               {
                   data&&data.length>0? data.map((item,index)=>{
                       return <div key={index} className="item">
                           <div>
                                <p>id:{item.id}</p>
                                <p>value :{item.value }</p>
                                <p>date :{item.date }</p>
                           </div>
                            <div>
                                <Button type="primary" onClick={()=>edit_data(item)}>编辑</Button>
                                <Button type="danger" onClick={()=>del_data(item.id)}>删除</Button>
                            </div>
                       </div>
                   }):"暂无数据"
               }
           </div>
          <My_dialog {...my_dialog}></My_dialog>
        </div>
    )
}

export default Todulist